package org.jash.ting13.service

import android.content.Context
import android.net.Uri
import androidx.annotation.OptIn
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.DefaultHttpDataSource
import androidx.media3.datasource.ResolvingDataSource
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import androidx.media3.exoplayer.source.MediaSource
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import org.jash.ting13.entity.PlayUrl
import org.jash.ting13.net.APIService
import org.jash.utils.net.service

private val service: APIService = service()
private val gson: Gson = GsonBuilder().create()

@OptIn(UnstableApi::class)
fun Context.mediaSourceFactory(): MediaSource.Factory =
    DefaultMediaSourceFactory(this).setDataSourceFactory(ResolvingDataSource.Factory(DefaultHttpDataSource.Factory()) {
        val play = service.getPlay(it.uri.toString())
        val s = service.getUrl(play.sc, play.sp, play.nid, play.cid, play.sort)
        val playUrl = gson.fromJson(s, PlayUrl::class.java)
        it.withUri(Uri.parse(playUrl.url))
    })
